package com.stox.manager;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;

import com.stox.event.NewBarsEvent;
import com.stox.event.NewScripEvent;
import com.stox.model.Bar;
import com.stox.model.Scrip;
import com.stox.repository.BarRepository;

@Component
public class BarManager implements SmartApplicationListener {

	@Autowired
	private BarRepository barRepository;
	
	public int getOrder() {
		return 3;
	}
		
	@SuppressWarnings("unchecked")
	public void onApplicationEvent(ApplicationEvent event) {
		if(NewScripEvent.class.isAssignableFrom(event.getClass())){
			Scrip scrip = (Scrip)event.getSource();
			barRepository.createPartition(scrip.getCode());
		}else if(NewBarsEvent.class.isAssignableFrom(event.getClass())){
			List<Bar> bars = (List<Bar>)event.getSource();
			save(bars);
		}
	}
	
	public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
		return NewScripEvent.class.isAssignableFrom(eventType) || 
				NewBarsEvent.class.isAssignableFrom(eventType);
	}
	
	public boolean supportsSourceType(Class<?> sourceType) {
		return Scrip.class.isAssignableFrom(sourceType) || 
				List.class.isAssignableFrom(sourceType);
	}
	
	public List<Bar> findByScripCode(String scripCode) {
		return barRepository.findByScripCode(scripCode);
	}

	public List<Bar> findByScripCode(String scripCode, final Date start) {
		return barRepository.findByScripCode(scripCode, start);
	}

	public List<Bar> findByScripCode(String scripCode, final int count) {
		return barRepository.findByScripCode(scripCode, count);
	}
	
	public List<Bar> findByScripCode(String scripCode, Date start, Date end) {
		return barRepository.findByScripCode(scripCode, start, end);
	}

	private Bar save(Bar bar){
		return barRepository.save(bar);
	}
	
	private void save(Iterable<Bar> bars){
		for(Bar bar : bars){
			save(bar);
		}
	}
}
